package models

import (
	"errors"
	"time"
)

type EnterAdvertisement struct {
	Id            int       `json:"id"`
	Title         string    `json:"title"`
	Icon          string    `json:"icon"`
	Broadcast     string    `json:"broadcast"`
	Money         float64   `json:"money"`
	SurvivalBegin time.Time `json:"survival_begin"`
	SurvivalEnd   time.Time `json:"survival_end"`
	Status        int       `json:"status"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
}

func AddEnterAdvertisement(data map[string]interface{}) error {
	loc, _ := time.LoadLocation("Asia/Chongqing")
	formateBegin, err := time.ParseInLocation("2006-01-02 15:04:05", data["survivalBegin"].(string)+" 00:00:00", loc)
	if err != nil {
		formateBegin = time.Now().In(loc)
	}
	formateEnd, err := time.ParseInLocation("2006-01-02 15:04:05", data["survivalEnd"].(string)+" 00:00:00", loc)
	if err != nil {
		return errors.New("到期时间转换错误")
	}
	m := DB.Table("enterprise_advertisement").Create(&EnterAdvertisement{
		Title:         data["title"].(string),
		Icon:          data["icon"].(string),
		Broadcast:     data["broadcast"].(string),
		Money:         data["money"].(float64),
		SurvivalBegin: formateBegin,
		SurvivalEnd:   formateEnd,
	})
	if m.Error != nil {
		return errors.New(m.Error.Error())
	}

	return nil
}

func GetEnterAds(page, limit int, status, beginTime, endTime string) (interface{}, *Paginator) {
	var res []*EnterAdvertisement
	m := DB.Table("enterprise_advertisement").Order("id DESC")

	if status != "" {
		m.Where("status = ? ", status)
	}
	if beginTime != "" {
		m.Where("created_at > ? ", beginTime)
	}
	if endTime != "" {
		m.Where("created_at < ? ", endTime)
	}
	var count int
	m.Count(&count)
	paginate := NewPage(page, limit, count)

	err := m.Offset(paginate.Offset).Limit(paginate.Limit).Find(&res).Error
	if err != nil {
		return nil, nil
	}

	return res, &paginate
}

func GetEnterAd(id int) (enterAd EnterAdvertisement) {
	DB.Table("enterprise_advertisement").Where("id = ?", id).First(&enterAd)
	return
}

func ExistEnterAdByID(id int) bool {
	var enterAd EnterAdvertisement
	DB.Table("enterprise_advertisement").Select("id").Where("id = ?", id).First(&enterAd)

	if enterAd.Id > 0 {
		return true
	}

	return false
}

func EditEnterAdByID(id int, data interface{}) bool {
	err := DB.Table("enterprise_advertisement").Where("id = ?", id).Updates(data)
	if err.Error != nil {
		return false
	}
	return true
}

func DeleteEnterAd(id int) bool {
	err := DB.Table("enterprise_advertisement").Where("id = ?", id).Delete(EnterAdvertisement{})

	if err.Error != nil {
		return false
	}
	return true
}
